package ch.unisi.inf.editor;

import java.awt.Color;
import java.util.ArrayList;
import ch.unisi.inf.engine.Image;
/**
 * this filter replaces a pixel with the average RGB value of the neighbors
 * 
 * @author matthias.eberli@lu.unisi.ch
 */
public class SmoothFilter extends Filter
{
    Image tempImage;
    
    public SmoothFilter(final String name)
    {
        super(name);
    }
    
    public void apply(final Image image)
    {
        tempImage = new Image(image.getPath(), image);
        final int height = image.getHeight();
        final int width = image.getWidth();
        for(int y = 0; y < height; y++) {
            for(int x = 0; x < width; x++) {
                 Color pixel = getAverageColor(tempImage, x, y);
                image.setPixel(x, y, pixel);
            }
        }
    }   
    
    /**
     * returns the color of the pixel if the pixel is inside the image
     * else it returns null
     */
    public Color getExistingPixel(final Image image, final int x, final int y)
    {
        final int height = image.getHeight();
        final int width = image.getWidth();
        if (x >= width || x < 0 || y >= height || y < 0){
            return null;
        }
        Color pixel = image.getPixel(x,y);
        return pixel;
    }
    
    /**
     * computes the average of the nine neighbor-pixel by first creating a list of
     * all the neighbors and then iterating through them and summing the RGB values
     * at the end it returns the average color of the 9 neighbors (or less if the pixel is, for example,
     * in a corner)
     */
    private Color getAverageColor(final Image image, final int x, final int y)
    {
        ArrayList<Color> list = new ArrayList<Color>();
        list.add(getExistingPixel(image, x,y));
        list.add(getExistingPixel(image, x,y+1));
        list.add(getExistingPixel(image, x,y-1));
        list.add(getExistingPixel(image, x+1,y));
        list.add(getExistingPixel(image, x+1,y+1));
        list.add(getExistingPixel(image, x+1,y-1));
        list.add(getExistingPixel(image, x-1,y));
        list.add(getExistingPixel(image, x-1,y+1));
        list.add(getExistingPixel(image, x-1,y-1));
        int counter = 0;
        int redValue = 0;
        int greenValue = 0;
        int blueValue = 0;
        
        for(Color color : list){
            if(color != null){
                counter++;
                redValue += color.getRed();
                greenValue += color.getGreen();
                blueValue += color.getBlue();
            }
        }
        return new Color(redValue/counter, greenValue/counter, blueValue/counter);
    }
}

